<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户管理</title>
    <script src="/assets/tailwind.js"></script>
    <link href="/assets/fontawesome-free-6.7.2-web/css/all.min.css" rel="stylesheet">
    <script src="/assets/qrcode.min.js"></script>
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#165DFF',
                        secondary: '#4080FF',
                        success: '#00B42A',
                        warning: '#FF7D00',
                        danger: '#F53F3F',
                        dark: '#1D2129',
                        light: '#F2F3F5',
                    },
                    fontFamily: {
                        inter: ['Inter', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .bg-gradient-blue {
                background: linear-gradient(135deg, #165DFF 0%, #4080FF 100%);
            }
            .shadow-card {
                box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
            }
            .transition-all-300 {
                transition: all 0.3s ease;
            }
            .tab-active {
                @apply border-primary text-primary;
            }
            .table-row-hover {
                @apply hover:bg-gray-50 transition-all-300;
            }
        }
    </style>
</head>
<body class="bg-gray-50 font-inter text-dark min-h-screen flex flex-col">
    <!-- 顶部导航栏 -->
    <header class="bg-white shadow-sm sticky top-0 z-50">
        <div class="container mx-auto px-4 py-3 flex items-center justify-between">
            <div class="flex items-center space-x-2">
                <i class="fa fa-shield text-primary text-xl"></i>
                <h1 class="text-xl font-bold text-primary">管理员控制台</h1>
            </div>
            <nav class="hidden md:flex items-center space-x-6">
                <a href="." class="text-primary transition-all-300 flex items-center">
                    <i class="fa fa-tachometer mr-2"></i> 首页
                </a>
                <a href="admin-settings" class="text-gray-600 hover:text-primary transition-all-300 flex items-center">
                    <i class="fa fa-user-circle mr-2"></i> 密码设置
                </a>
            </nav>
            <div class="flex items-center space-x-4">
                <a href="." class="text-gray-600 hover:text-primary transition-all duration-300 inline-block">
                    <i class="fa fa-bell text-xl"></i>
                </a>
                <div class="relative">
                    <button class="flex items-center space-x-2 focus:outline-none" id="adminDropdownBtn">
                        <img src="https://picsum.photos/200/200?random=1" alt="管理员头像" class="w-8 h-8 rounded-full object-cover border-2 border-primary">
                        <span class="hidden md:inline-block font-medium">admin</span>
                        <i class="fa fa-angle-down text-gray-500"></i>
                    </button>
                    <!-- 下拉菜单（使用 Tailwind 类控制样式和交互） -->
                    <ul id="adminDropdownMenu" class="absolute right-0 mt-2 w-48 bg-white shadow-lg rounded-lg py-1 hidden">
                        <li>
                        <a href="admin-settings" 
                            class="block px-4 py-2 text-sm text-gray-700 hover:bg-primary hover:text-white transition-colors">
                            <i class="fa fa-key mr-2"></i> 修改密码
                        </a>
                        </li>
                        <li>
                        <a href="logout" 
                            class="block px-4 py-2 text-sm text-gray-700 hover:bg-primary hover:text-white transition-colors">
                            <i class="fa fa-sign-out-alt mr-2"></i> 登出
                        </a>
                        </li>
                    </ul>
                </div>
                <button class="md:hidden text-gray-600 hover:text-primary transition-all-300">
                    <i class="fa fa-bars text-xl"></i>
                </button>
            </div>
        </div>
    </header>

    <!-- 主要内容区 -->
    <main class="flex-grow container mx-auto px-4 py-8">
        <div class="max-w-5xl mx-auto">
            <!-- 页面标题 -->
            <div class="mb-8">
                <h2 class="text-[clamp(1.5rem,3vw,2.5rem)] font-bold text-dark mb-2">用户管理</h2>
                <p class="text-gray-500">管理系统用户信息</p>
            </div>

            <!-- 用户管理卡片 -->
            <div id="content-users" class="bg-white rounded-xl shadow-card p-6 mb-8">
                <div class="flex flex-col md:flex-row md:items-center md:justify-between mb-6">
                    <h3 class="text-xl font-bold mb-4 md:mb-0">用户管理</h3>
                    <div class="flex space-x-4">
                        <div class="relative">
                            <input type="text" id="user-search" placeholder="搜索用户..." 
                                class="pl-10 pr-4 py-2 rounded-lg border border-gray-300 focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all-300 w-full md:w-64">
                            <i class="fa fa-search absolute left-3 top-1/2 -translate-y-1/2 text-gray-400"></i>
                        </div>
                        <button id="add-user-btn" class="px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-all-300 flex items-center shadow-sm hover:shadow">
                            <i class="fa fa-plus mr-2"></i> 添加用户
                        </button>
                    </div>
                </div>

                <!-- 用户列表 -->
                <div class="overflow-x-auto">
                    <table class="min-w-full divide-y divide-gray-200">
                        <thead class="bg-gray-50">
                            <tr>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">ID</th>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">头像</th>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">用户名</th>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">邮箱</th>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">角色</th>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
                                <th scope="col" class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                            </tr>
                        </thead>
                        <tbody id="user-list" class="bg-white divide-y divide-gray-200">
                            <!-- 用户数据将通过JavaScript动态生成 -->
                        </tbody>
                    </table>
                </div>

                <!-- 分页控件 -->
                <div id="paginationControls" class="flex items-center justify-between px-4 py-3 sm:px-6 mt-4">
                    <div class="hidden sm:flex-1 sm:flex sm:items-center sm:justify-between">
                        <div>
                            <p id="paginationInfo" class="text-sm text-gray-700">
                                显示第 <span class="font-medium">1</span> 到 <span class="font-medium">10</span> 条，共 <span class="font-medium">24</span> 条记录
                            </p>
                        </div>
                        <div>
                            <nav id="paginationNav" class="relative z-0 inline-flex rounded-md shadow-sm -space-x-px" aria-label="Pagination">
                                <!-- 分页按钮将动态生成 -->
                            </nav>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 添加/编辑用户模态框 -->
            <div id="user-modal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
                <div class="bg-white rounded-xl shadow-xl max-w-md w-full mx-4 transform transition-all duration-300 scale-95 opacity-0" id="modal-content">
                    <div class="flex items-center justify-between p-6 border-b">
                        <h3 class="text-lg font-medium text-gray-900" id="modal-title">添加用户</h3>
                        <button id="close-modal" class="text-gray-400 hover:text-gray-500 focus:outline-none">
                            <i class="fa fa-times text-xl"></i>
                        </button>
                    </div>
                    <div class="p-6">
                        <form id="user-form" class="space-y-6">
                            <input type="hidden" id="user-id" value="">
                            
                            <div class="space-y-2">
                                <label for="user-name" class="block text-sm font-medium text-gray-700">用户名</label>
                                <input type="text" id="user-name" name="user-name" 
                                    class="w-full px-4 py-3 rounded-lg border border-gray-300 focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all-300"
                                    placeholder="请输入用户名">
                            </div>
                            
                            <div class="space-y-2">
                                <label for="user-email" class="block text-sm font-medium text-gray-700">邮箱</label>
                                <input type="email" id="user-email" name="user-email" 
                                    class="w-full px-4 py-3 rounded-lg border border-gray-300 focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all-300"
                                    placeholder="请输入邮箱">
                            </div>
                            
                            <div class="space-y-2">
                                <label for="user-password" class="block text-sm font-medium text-gray-700">密码</label>
                                <input type="password" id="user-password" name="user-password" 
                                    class="w-full px-4 py-3 rounded-lg border border-gray-300 focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all-300"
                                    placeholder="请输入密码">
                            </div>
                            
                            <div class="space-y-2">
                                <label for="user-role" class="block text-sm font-medium text-gray-700">角色</label>
                                <select id="user-role" name="user-role" 
                                    class="w-full px-4 py-3 rounded-lg border border-gray-300 focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all-300">
                                    <option value="configer">配置员</option>
                                    <option value="admin">管理员</option>
                                    <option value="auditor">审计员</option>
                                </select>
                            </div>

                            <!-- 预留一个容器，可选项目会插到这里 -->
                            <div id="extra-privilege" class="space-y-4 mt-4"></div>

                            <div class="space-y-2">
                                <label class="block text-sm font-medium text-gray-700">状态</label>
                                <div class="flex items-center space-x-4">
                                    <label class="inline-flex items-center">
                                        <input type="radio" name="user-status" value="active" class="text-primary focus:ring-primary h-4 w-4" checked>
                                        <span class="ml-2">活跃</span>
                                    </label>
                                    <label class="inline-flex items-center">
                                        <input type="radio" name="user-status" value="inactive" class="text-primary focus:ring-primary h-4 w-4">
                                        <span class="ml-2">禁用</span>
                                    </label>
                                </div>
                            </div>
                        </form>
                    </div>
                    <div class="flex justify-end p-6 border-t space-x-4">
                        <button id="cancel-user-btn" class="px-6 py-3 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition-all-300 flex items-center">
                            取消
                        </button>
                        <button id="save-user-btn" class="px-6 py-3 bg-primary text-white rounded-lg hover:bg-primary/90 transition-all-300 flex items-center shadow-md hover:shadow-lg">
                            保存
                        </button>
                    </div>
                </div>
            </div>

            <!-- 删除用户确认模态框 -->
            <div id="delete-modal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
                <div class="bg-white rounded-xl shadow-xl max-w-md w-full mx-4 transform transition-all duration-300 scale-95 opacity-0" id="delete-modal-content">
                    <div class="p-6">
                        <div class="text-center">
                            <div class="mx-auto flex items-center justify-center h-12 w-12 rounded-full bg-danger/10 mb-4">
                                <i class="fa fa-trash text-danger text-xl"></i>
                            </div>
                            <h3 class="text-lg font-medium text-gray-900 mb-2">确认删除</h3>
                            <p class="text-gray-500 mb-6" id="delete-message">你确定要删除这个用户吗？此操作不可撤销。</p>
                        </div>
                        <div class="flex justify-center space-x-4">
                            <button id="cancel-delete-btn" class="px-6 py-3 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition-all-300 flex items-center">
                                取消
                            </button>
                            <button id="confirm-delete-btn" class="px-6 py-3 bg-danger text-white rounded-lg hover:bg-danger/90 transition-all-300 flex items-center shadow-md hover:shadow-lg">
                                <i class="fa fa-trash mr-2"></i> 删除
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 操作结果提示 -->
            <div id="result-message" class="hidden p-4 rounded-lg mb-6 transition-all-300 transform translate-y-4 opacity-0">
                <div id="success-message" class="hidden bg-success/10 border border-success/20 text-success p-4 rounded-lg">
                    <div class="flex items-start">
                        <div class="flex-shrink-0 pt-0.5">
                            <i class="fa fa-check-circle text-xl"></i>
                        </div>
                        <div class="ml-3">
                            <h3 class="text-sm font-medium">操作成功</h3>
                            <div class="mt-2 text-sm">
                                <p id="success-text">操作已成功完成。</p>
                            </div>
                        </div>
                    </div>
                </div>
                <div id="error-message" class="hidden bg-danger/10 border border-danger/20 text-danger p-4 rounded-lg">
                    <div class="flex items-start">
                        <div class="flex-shrink-0 pt-0.5">
                            <i class="fa fa-exclamation-circle text-xl"></i>
                        </div>
                        <div class="ml-3">
                            <h3 class="text-sm font-medium">操作失败</h3>
                            <div class="mt-2 text-sm">
                                <p id="error-text">操作未能完成，请重试。</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </main>

    <!-- 页脚 -->
    <footer class="bg-white border-t border-gray-200 py-6">
        <div class="container mx-auto px-4">
            <div class="flex flex-col md:flex-row justify-between items-center">
                <div class="mb-4 md:mb-0">
                    <p class="text-gray-500 text-sm">&copy; 2025 北京椰子树信息技术有限公司. 保留所有权利.</p>
                </div>
                <div class="flex space-x-6">
                    <a href="http://www.coconet.cn" class="text-gray-500 hover:text-primary transition-all-300">
                        <i class="fa fa-question-circle mr-1"></i> 帮助中心
                    </a>
                    <a href="http://www.coconet.cn" class="text-gray-500 hover:text-primary transition-all-300">
                        <i class="fa fa-file-text-o mr-1"></i> 隐私政策
                    </a>
                    <a href="mailto:goodput3@qq.com" class="text-gray-500 hover:text-primary transition-all-300">
                        <i class="fa fa-phone mr-1"></i> 联系我们
                    </a>
                </div>
            </div>
        </div>
    </footer>

    <script>
        // 模拟用户数据
        let users = [
            { id: 1, username: '张三', email: 'zhangsan@example.com', role: 'admin', status: 'active', avatar: 'https://picsum.photos/200/200?random=1' },
            { id: 2, username: '李四', email: 'lisi@example.com', role: 'configer', status: 'active', avatar: 'https://picsum.photos/200/200?random=2' },
            { id: 3, username: '王五', email: 'wangwu@example.com', role: 'auditor', status: 'inactive', avatar: 'https://picsum.photos/200/200?random=3' },
            { id: 4, username: '赵六', email: 'zhaoliu@example.com', role: 'configer', status: 'active', avatar: 'https://picsum.photos/200/200?random=4' },
            { id: 5, username: '钱七', email: 'qianqi@example.com', role: 'configer', status: 'active', avatar: 'https://picsum.photos/200/200?random=5' },
            { id: 6, username: '孙八', email: 'sunba@example.com', role: 'auditor', status: 'inactive', avatar: 'https://picsum.photos/200/200?random=6' },
            { id: 7, username: '周九', email: 'zhoujiu@example.com', role: 'configer', status: 'active', avatar: 'https://picsum.photos/200/200?random=7' },
            { id: 8, username: '吴十', email: 'wushi@example.com', role: 'configer', status: 'inactive', avatar: 'https://picsum.photos/200/200?random=8' },
            { id: 9, username: '郑十一', email: 'zhengshiyi@example.com', role: 'admin', status: 'active', avatar: 'https://picsum.photos/200/200?random=9' },
            { id: 10, username: '王十二', email: 'wangshier@example.com', role: 'configer', status: 'active', avatar: 'https://picsum.photos/200/200?random=10' }
        ];

        // 渲染用户列表
        async function renderUserList() {
            const userList = document.getElementById('user-list');
            userList.innerHTML = '';

            const response = await fetch('/listusers', {
                method: 'GET',
                headers: { 'Content-Type': 'application/json' }
            });
            if (!response.ok) throw new Error(`HTTP error! Status: ${response.status}`);

            users = await response.json();
            initPagination(users);

            const startIndex = (paginationConfig.currentPage - 1) * paginationConfig.pageSize;
            const endIndex   = Math.min(startIndex + paginationConfig.pageSize, users.length);
            const usersToDisplay = users.slice(startIndex, endIndex);

            usersToDisplay.forEach(user => {
                const statusClass = user.status === 'active' ? 'bg-success/10 text-success' : 'bg-gray/10 text-gray';
                const statusText  = user.status === 'active' ? '活跃' : '禁用';
                const roleText    = user.role === 'admin'   ? '管理员'
                                : user.role === 'auditor' ? '审计员'
                                                        : '配置员';

                // 只有配置员才渲染额外 3 列
                const isConfig = user.role === 'configer';
                const extraCols = isConfig
                    ? `<td class="px-6 py-4 text-sm text-gray-500">${user.accessdir  || '-'}</td>
                    <td class="px-6 py-4 text-sm text-gray-500">${user.uploadperm ? '允许' : '禁止'}</td>
                    <td class="px-6 py-4 text-sm text-gray-500">${user.downloadperm ? '允许' : '禁止'}</td>`
                    : `<td></td><td></td><td></td>`;   // 占位，防止列错位

                const row = document.createElement('tr');
                row.className = 'table-row-hover';
                row.innerHTML = `
                    <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">${user.id}</td>
                    <td class="px-6 py-4 whitespace-nowrap">
                        <div class="flex items-center">
                            <img class="h-10 w-10 rounded-full object-cover" src="${user.avatar}" alt="${user.username}">
                        </div>
                    </td>
                    <td class="px-6 py-4">
                        <div class="text-sm font-medium text-gray-900">${user.username}</div>
                        <div class="text-sm text-gray-500">${user.email}</div>
                    </td>
                    <td class="px-6 py-4 text-sm text-gray-500">${user.email}</td>
                    <td class="px-6 py-4 whitespace-nowrap">
                        <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-primary/10 text-primary">${roleText}</span>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap">
                        <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${statusClass}">${statusText}</span>
                    </td>
                    ${extraCols}
                    <td class="px-6 py-4 text-right text-sm font-medium">
                        <button class="text-primary hover:text-primary/80 mr-3 edit-user" data-id="${user.id}">
                            <i class="fa fa-edit"></i> 编辑
                        </button>
                        <button class="text-danger hover:text-danger/80 delete-user" data-id="${user.id}">
                            <i class="fa fa-trash"></i> 删除
                        </button>
                    </td>
                `;
                userList.appendChild(row);
            });

            // 绑定按钮事件（保持不变）
            document.querySelectorAll('.edit-user').forEach(btn => {
                btn.addEventListener('click', () => openEditUserModal(parseInt(btn.dataset.id)));
            });
            document.querySelectorAll('.delete-user').forEach(btn => {
                btn.addEventListener('click', () => openDeleteUserModal(parseInt(btn.dataset.id)));
            });
        }

        // 打开添加用户模态框
        document.getElementById('add-user-btn').addEventListener('click', function() {
            document.getElementById('modal-title').textContent = '添加用户';
            document.getElementById('user-id').value = '';
            document.getElementById('user-form').reset();
            document.getElementById('user-password').required = true;
            
            openModal('user-modal');
        });

        // 打开编辑用户模态框
        function openEditUserModal(userId) {
            const user = users.find(u => u.id === userId);
            if (!user) return;
            
            document.getElementById('modal-title').textContent = '编辑用户';
            document.getElementById('user-id').value = user.id;
            document.getElementById('user-name').value = user.username;
            document.getElementById('user-email').value = user.email;
            document.getElementById('user-password').value = '';
            document.getElementById('user-password').required = false;
            document.getElementById('user-role').value = user.role;
            
            // 设置状态
            if (user.status === 'active') {
                document.querySelector('input[name="user-status"][value="active"]').checked = true;
            } else {
                document.querySelector('input[name="user-status"][value="inactive"]').checked = true;
            }
            
            openModal('user-modal');
        }

        // 打开删除用户模态框
        function openDeleteUserModal(userId) {
            const user = users.find(u => u.id === userId);
            if (!user) return;
            
            document.getElementById('delete-message').textContent = `你确定要删除用户 "${user.username}" 吗？此操作不可撤销。`;
            document.getElementById('confirm-delete-btn').dataset.id = userId;
            
            openModal('delete-modal');
        }

        // 打开模态框
        function openModal(modalId) {
            const modal = document.getElementById(modalId);
            const modalContent = document.getElementById(modalId === 'user-modal' ? 'modal-content' : 'delete-modal-content');
            
            modal.classList.remove('hidden');
            setTimeout(() => {
                modalContent.classList.remove('scale-95', 'opacity-0');
                modalContent.classList.add('scale-100', 'opacity-100');
            }, 10);
        }

        // 关闭模态框
        function closeModal(modalId) {
            const modal = document.getElementById(modalId);
            const modalContent = document.getElementById(modalId === 'user-modal' ? 'modal-content' : 'delete-modal-content');
            
            modalContent.classList.remove('scale-100', 'opacity-100');
            modalContent.classList.add('scale-95', 'opacity-0');
            
            setTimeout(() => {
                modal.classList.add('hidden');
            }, 300);
        }

        // 关闭用户模态框
        document.getElementById('close-modal').addEventListener('click', function() {
            closeModal('user-modal');
        });

        // 取消添加/编辑用户
        document.getElementById('cancel-user-btn').addEventListener('click', function() {
            closeModal('user-modal');
        });

        // 取消删除用户
        document.getElementById('cancel-delete-btn').addEventListener('click', function() {
            closeModal('delete-modal');
        });

        // 保存用户
        document.getElementById('save-user-btn').addEventListener('click', async function() {
            const userId = document.getElementById('user-id').value || 0;
            const name = document.getElementById('user-name').value;
            const email = document.getElementById('user-email').value;
            const password = document.getElementById('user-password').value;
            const role = document.getElementById('user-role').value;
            const status = document.querySelector('input[name="user-status"]:checked').value;
            const dirInput = document.querySelector('input[name="access_dir"]');
            const accessdir = dirInput ? dirInput.value.trim() : '';
            const upStatus = document.querySelector('input[name="upload_privilege"]:checked');
            const uploadperm = upStatus ? upStatus.value == "1": false;
            const downStatus = document.querySelector('input[name="download_privilege"]:checked');
            const downloadperm = downStatus ? downStatus.value == "1" : false;

            console.log("user id: ", userId);
            if (!name || !email) {
                showResultMessage(false, '用户名和邮箱不能为空');
                return;
            }
            
            if (!password) {
                showResultMessage(false, '添加用户时密码不能为空');
                return;
            }
            if(password.length < 4 || password.length > 160) {
                showResultMessage(false, '密码长度必须在4到160个字符之间');
                return;
            }
            const result = await fetch('/adduser', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    id: Number(userId),
                    username: name,
                    password: password,
                    role: role,
                    email: email,
                    status: status,
                    created_at: new Date().toISOString(),
                    avatar: '',
                    accessdir: accessdir,
                    uploadperm: uploadperm,
                    downloadperm: downloadperm
                }),
            })
            .then(response => {
                console.log("response is ", response);
                if (!response.ok) {
                    showResultMessage(true, '用户添加失败');
                    renderUserList();
                    closeModal('user-modal');
                    return "添加失败";
                }
                showResultMessage(true, '用户已成功添加');
                renderUserList();
                closeModal('user-modal');
                return "添加成功";
            })
            .catch(error => {
                console.error('add user failed:', error);
                // Return empty results or handle error appropriately
                return [];
            }); 
            //console.log("delete result of id ", result, id);            
            // 模拟API调用
            setTimeout(() => {
                if (userId) {
                    // 更新用户
                    const index = users.findIndex(u => u.id === parseInt(userId));
                    if (index !== -1) {
                        users[index] = {
                            ...users[index],
                            name,
                            email,
                            role,
                            status
                        };
                        showResultMessage(true, '用户信息已更新');
                    }
                } else {
                    // 添加用户
                    const newId = Math.max(...users.map(u => u.id)) + 1;
                    users.push({
                        id: newId,
                        name,
                        email,
                        role,
                        status,
                        avatar: `https://picsum.photos/200/200?random=${newId}`,
                    });
                    showResultMessage(true, '用户已成功添加');
                }
                
                renderUserList();
                closeModal('user-modal');
            }, 800);
        });

        // 确认删除用户
        document.getElementById('confirm-delete-btn').addEventListener('click', async function() {
            const id = parseInt(this.dataset.id);
            const result = await fetch('/deleteuser', {
                method: 'DELETE',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: id,
            })
            .then(response => {
                console.log("response is ", response);
                if (!response.ok) {
                    showResultMessage(true, '用户删除失败');
                    return "删除失败";
                }
                showResultMessage(true, '用户已成功删除');
                return "删除成功";
            })
            .catch(error => {
                console.error('delete failed:', error);
                // Return empty results or handle error appropriately
                return [];
            }); 
            //console.log("delete result of id ", result, id);    
            setTimeout(() => {
                showResultMessage(true, '用户已成功删除');
                renderUserList();
                closeModal('delete-modal');
            }, 800);       
        });

        // 搜索用户
        document.getElementById('user-search').addEventListener('input', function() {
            const searchTerm = this.value.toLowerCase().trim();
            
            // 过滤用户
            const filteredUsers = users.filter(user => 
                user.name.toLowerCase().includes(searchTerm) || 
                user.email.toLowerCase().includes(searchTerm)
            );
            
            // 渲染过滤后的用户列表
            const userList = document.getElementById('user-list');
            userList.innerHTML = '';
            
            if (filteredUsers.length === 0) {
                const emptyRow = document.createElement('tr');
                emptyRow.innerHTML = `
                    <td colspan="7" class="px-6 py-10 text-center">
                        <div class="text-gray-500">
                            <i class="fa fa-search text-3xl mb-2 opacity-30"></i>
                            <p>没有找到匹配的用户</p>
                        </div>
                    </td>
                `;
                userList.appendChild(emptyRow);
                return;
            }
            
            filteredUsers.forEach(user => {
                const statusClass = user.status === 'active' ? 'bg-success/10 text-success' : 'bg-gray/10 text-gray';
                const statusText = user.status === 'active' ? '活跃' : '禁用';
                const roleText = user.role === 'admin' ? '管理员' : user.role === 'auditor' ? '审计员' : '配置员';
                
                const row = document.createElement('tr');
                row.className = 'table-row-hover';
                row.innerHTML = `
                    <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">${user.id}</td>
                    <td class="px-6 py-4 whitespace-nowrap">
                        <div class="flex items-center">
                            <div class="flex-shrink-0 h-10 w-10">
                                <img class="h-10 w-10 rounded-full object-cover" src="${user.avatar}" alt="${user.name}">
                            </div>
                        </div>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap">
                        <div class="text-sm font-medium text-gray-900">${user.name}</div>
                        <div class="text-sm text-gray-500">${user.email}</div>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${user.email}</td>
                    <td class="px-6 py-4 whitespace-nowrap">
                        <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-primary/10 text-primary">
                            ${roleText}
                        </span>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap">
                        <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${statusClass}">
                            ${statusText}
                        </span>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                        <button class="text-primary hover:text-primary/80 mr-3 edit-user" data-id="${user.id}">
                            <i class="fa fa-edit"></i> 编辑
                        </button>
                        <button class="text-danger hover:text-danger/80 delete-user" data-id="${user.id}">
                            <i class="fa fa-trash"></i> 删除
                        </button>
                    </td>
                `;
                
                userList.appendChild(row);
            });
        });

        // 显示操作结果消息
        function showResultMessage(success, message) {
            const resultMessage = document.getElementById('result-message');
            const successMessage = document.getElementById('success-message');
            const errorMessage = document.getElementById('error-message');
            const successText = document.getElementById('success-text');
            const errorText = document.getElementById('error-text');

            resultMessage.classList.remove('hidden');
            resultMessage.classList.add('translate-y-0', 'opacity-100');

            if (success) {
                successMessage.classList.remove('hidden');
                errorMessage.classList.add('hidden');
                successText.textContent = message;
            } else {
                successMessage.classList.add('hidden');
                errorMessage.classList.remove('hidden');
                errorText.textContent = message;
            }

            setTimeout(() => {
                resultMessage.classList.add('translate-y-4', 'opacity-0');
                setTimeout(() => {
                    resultMessage.classList.add('hidden');
                }, 300);
            }, 3000);
        }
        const dropdownBtn = document.getElementById('adminDropdownBtn');
        const dropdownMenu = document.getElementById('adminDropdownMenu');
      
        // 切换菜单显示状态
        dropdownBtn.addEventListener('click', () => {
          dropdownMenu.classList.toggle('hidden');
          // 切换箭头旋转动画（可选）
          dropdownBtn.querySelector('.fa-angle-down').classList.toggle('rotate-180');
        });
      
        // 点击外部关闭菜单
        window.addEventListener('click', (event) => {
          if (!event.target.closest('#adminDropdownBtn, #adminDropdownMenu')) {
            dropdownMenu.classList.add('hidden');
            dropdownBtn.querySelector('.fa-angle-down').classList.remove('rotate-180');
          }
        });
        // 分页相关配置
        const paginationConfig = {
            currentPage: 1,         // 当前页码
            pageSize: 10,           // 每页显示数量
            maxVisiblePages: 5,     // 最多显示的页码按钮数量
            totalItems: 0,          // 总记录数
            totalPages: 0,          // 总页数
            users: []               // 用户数据
        };

        // 初始化分页控件
        function initPagination(users) {
            paginationConfig.users = users;
            paginationConfig.totalItems = users.length;
            paginationConfig.totalPages = Math.ceil(users.length / paginationConfig.pageSize);
            
            renderPaginationControls();
        }

        // 渲染分页控件
        function renderPaginationControls() {
            const navElement = document.getElementById('paginationNav');
            const infoElement = document.getElementById('paginationInfo');
            navElement.innerHTML = '';
            const { currentPage, totalPages, pageSize, totalItems } = paginationConfig;

            // 更新分页信息
            const startItem = Math.min((currentPage - 1) * pageSize + 1, totalItems);
            const endItem = Math.min(currentPage * pageSize, totalItems);
            infoElement.innerHTML = `
                显示第 <span class="font-medium">${startItem}</span> 到 <span class="font-medium">${endItem}</span> 条，共 <span class="font-medium">${totalItems}</span> 条记录
            `;

            // 添加上一页按钮
            const prevButton = document.createElement('a');
            prevButton.href = '#';
            prevButton.className = `relative inline-flex items-center px-2 py-2 rounded-l-md border border-gray-300 ${
                currentPage === 1 ? 'bg-gray-100 text-gray-400 cursor-not-allowed' : 'bg-white text-sm font-medium text-gray-500 hover:bg-gray-50'
            }`;
            prevButton.innerHTML = '<span class="sr-only">上一页</span><i class="fa fa-chevron-left text-xs"></i>';
            
            if (currentPage !== 1) {
                prevButton.addEventListener('click', () => goToPage(currentPage - 1));
            }
            navElement.appendChild(prevButton);

            // 计算显示的页码范围
            let startPage = Math.max(1, currentPage - Math.floor(paginationConfig.maxVisiblePages / 2));
            let endPage = Math.min(startPage + paginationConfig.maxVisiblePages - 1, totalPages);
            
            // 调整起始页码以确保显示完整的页码范围
            if (endPage - startPage + 1 < paginationConfig.maxVisiblePages) {
                startPage = Math.max(1, endPage - paginationConfig.maxVisiblePages + 1);
            }

            // 添加省略号（如果需要）
            if (startPage > 1) {
                addPageButton(1);
                if (startPage > 2) {
                    addEllipsis();
                }
            }

            // 添加页码按钮
            for (let i = startPage; i <= endPage; i++) {
                addPageButton(i);
            }

            // 添加省略号（如果需要）
            if (endPage < totalPages) {
                if (endPage < totalPages - 1) {
                    addEllipsis();
                }
                addPageButton(totalPages);
            }

            // 添加下一页按钮
            const nextButton = document.createElement('a');
            nextButton.href = '#';
            nextButton.className = `relative inline-flex items-center px-2 py-2 rounded-r-md border border-gray-300 ${
                currentPage === totalPages ? 'bg-gray-100 text-gray-400 cursor-not-allowed' : 'bg-white text-sm font-medium text-gray-500 hover:bg-gray-50'
            }`;
            nextButton.innerHTML = '<span class="sr-only">下一页</span><i class="fa fa-chevron-right text-xs"></i>';
            
            if (currentPage !== totalPages) {
                nextButton.addEventListener('click', () => goToPage(currentPage + 1));
            }
            navElement.appendChild(nextButton);

            // 辅助函数：添加页码按钮
            function addPageButton(pageNum) {
                const button = document.createElement('a');
                button.href = '#';
                button.textContent = pageNum;
                button.className = `relative inline-flex items-center px-4 py-2 border border-gray-300 ${
                    pageNum === currentPage ? 'bg-primary text-sm font-medium text-white hover:bg-primary/90' : 'bg-white text-sm font-medium text-gray-700 hover:bg-gray-50'
                }`;
                
                if (pageNum !== currentPage) {
                    button.addEventListener('click', () => goToPage(pageNum));
                }
                navElement.appendChild(button);
            }

            // 辅助函数：添加省略号
            function addEllipsis() {
                const ellipsis = document.createElement('span');
                ellipsis.className = 'relative inline-flex items-center px-4 py-2 border border-gray-300 bg-white text-sm font-medium text-gray-700';
                ellipsis.textContent = '...';
                navElement.appendChild(ellipsis);
            }
        }

        // 跳转到指定页码
        function goToPage(pageNum) {
            if (pageNum < 1 || pageNum > paginationConfig.totalPages) return;
            
            paginationConfig.currentPage = pageNum;
            renderPaginationControls();
            renderUserList(); // 重新渲染用户列表
        }

        // 要插入的 HTML 片段
        const privilegeTpl = `
            <div class="space-y-2">
                <label class="block text-sm font-medium text-gray-700">可访问目录</label>
                <input type="text" name="access_dir" placeholder="例如 /data/config"
                    class="w-full px-4 py-3 rounded-lg border border-gray-300 focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all-300">
            </div>

            <div class="flex items-center space-x-4">
                <label class="flex items-center">
                <input type="checkbox" name="upload_privilege" value="1" class="rounded border-gray-300 text-primary focus:ring-primary">
                <span class="ml-2 text-sm text-gray-700">上传权限</span>
                </label>
                <label class="flex items-center">
                <input type="checkbox" name="download_privilege" value="1" class="rounded border-gray-300 text-primary focus:ring-primary">
                <span class="ml-2 text-sm text-gray-700">下载权限</span>
                </label>
            </div>
            `;

        const roleSelect = document.getElementById('user-role');
        const container  = document.getElementById('extra-privilege');
        const tpl        = privilegeTpl;   // 同上

        roleSelect.addEventListener('change', () => {
        if (roleSelect.value === 'configer') {
            if (!container.hasChildNodes()) {
            container.insertAdjacentHTML('beforeend', tpl);
            }
        } else {
            container.innerHTML = '';
        }
        });
        roleSelect.dispatchEvent(new Event('change'));

        // 初始化用户列表
        renderUserList();
    </script>
</body>
</html>
